package cn.fanyc.action.blockchain.fbc.org1.controller;

import cn.fanyc.action.blockchain.fbc.org1.config.GlobalConstants;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

/**
 * 页面请求控制器
 *
 * @author Fanyc
 * @date 2020/6/17 16:58
 */
@Controller
@RequestMapping("/")
public class HomeUIController {

    /**
     * Fabric网关
     */
    @Autowired
    private Gateway gateway;

    /**
     * 获取票据列表
     * @param modelMap 页面模型
     * @return 票据列表页面
     * @throws ContractException 合约异常
     */
    @RequestMapping({"", "/", "/index"})
    public String index(ModelMap modelMap) throws ContractException {
        // 获取区块链通道网络
        Network network = gateway.getNetwork(GlobalConstants.CHANNEL_NAME);

        // 获取合约
        Contract contract = network.getContract(GlobalConstants.CONTRACT_FBC);
        // 调用合约的获取票据列表方法
        byte[] result = contract.evaluateTransaction("getKeys");

        if (result != null && result.length > 0) {
            System.out.println("票据列表：" + new String(result));
            JSONArray keys = new JSONArray(new String(result));
            List<Map<String, String>> collect = keys.toList().stream().map(key -> {
                String[] split = key.toString().split(":");
                Map<String, String> value = new HashMap<>(2);
                value.put("issuer", split[0]);
                value.put("paperNumber", split[1]);
                value.put("key", key.toString());
                return value;
            }).collect(Collectors.toList());
            modelMap.put("keys", collect);
        } else {
            System.out.println("票据列表：[]");
            modelMap.put("keys", new ArrayList<>(0));
        }

        return "index";
    }
}
